//
//  OAuthViewController.swift
//  01-微博项目搭建
//
//  Created by Adolph on 15/5/14.
//  Copyright (c) 2015年 Adolph. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    let WB_Client_Id = "1947445174"
    let WB_Redirect_Uri = "http://itheima.com"
    let WB_Client_Secret = "743adbb69c5a42be85461b889ad37fed"
   
    /// 计算属性，只有 getter，是 ReadOnly
    var webView: UIWebView {
        return view as! UIWebView
    }
    
    ///关闭授权页,和取消SVProgressHUD
    @IBAction func closeBtb() {
        SVProgressHUD.dismiss()
        navigationController?.dismissViewControllerAnimated(true, completion:nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadAuthPage()
    }
    
    /**
    加载授权页面
    
    daoge10000@sina.cn
    
    1> https://api.weibo.com/
    2> 授权成功 回调地址开头 http://itheima.com/?code=8670711433faffa5d21a6a53b9df0095
    3> http://m.weibo.cn/reg/index
    4> http://login.sina.com.cn/sso/
    5> 用户取消授权 http://itheima.com/?error_uri=%
    
    分析：
    1> 如果 URL 以 https://api.weibo.com/ 开头就继续加载页面
    2> 如果 URL 以 http://itheima.com 开头，不用加载页面
    - 判断是否有 code，就是请求码
    3> 其他页面统一不加载
    */
    private func loadAuthPage(){
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_Client_Id + "&redirect_uri=" + WB_Redirect_Uri
        let url = NSURL(string: urlString)!
        //发送请求
        webView.loadRequest(NSURLRequest(URL: url))
      
    }
    
    // 如果系统方法返回 Bool 返回true，都能工作正常
    //webView 的代理
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       
        println(request.URL!)
        //取到URL 的完整字符串
        let urlString = request.URL!.absoluteString!
        //1. 如果是官方的页面就继续加载
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        //2. 判断 url 是否是设置的回调地址
        if !urlString.hasPrefix(WB_Redirect_Uri) {
           return false
        }
        // 3. 代码执行到这里，就一定是回调的地址
        // query 可以过滤掉协议头和主机地址，所有的参数部分取出
        println("------" + request.URL!.query!)
        
        let codeStr = "code="
        let query = request.URL!.query!
        
        if query.hasPrefix(codeStr) {
         //获取请求吗
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            println("验证码 " + code)
            loadAcessToken(code)
            
        }else {
           println("用户拒绝")
            //直接视图控制器，并关闭SVP
            closeBtb()
         }
        return false
     }
    
    private func loadAcessToken(code: String){
        let parms = [
            "client_id": WB_Client_Id,
            "client_secret": WB_Client_Secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_Redirect_Uri]
       
        UserAccount.loadAccessToken(parms, completion: { (account) -> () in
        if account != nil {
          //设置全局变量
            sharedUserAccount = account
         //发送通知， 前往Welcome
            NSNotificationCenter.defaultCenter().postNotificationName(showMainNotification, object: "Welecome")
            self.dismissViewControllerAnimated(true, completion: nil)
            return
        }
     })
    }
    
    ///开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    ///将要结束页面
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

}
